<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="100%"
  >

    <el-form :model="dataForm" :rules="dataRule"
             ref="dataForm" label-width="120px"

    >
      <!--             @keyup.enter.native="dataFormSubmit()" -->
      <div>
        <!--        <el-collapse v-model="infoVal">-->
        <!--          <el-collapse-item title="销售订单信息" name="1">-->
        <el-row>
          <el-form-item label="销售订单名" prop="name">
            <el-input v-model="dataForm.name" placeholder="销售订单名">
              <el-button slot="append" icon="el-icon-search" @click="getLastSaleOrder(dataForm)"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="客户" prop="clientName">
            <!--              <el-input v-model="dataForm.clientId" placeholder="客户"></el-input>-->
            <el-autocomplete v-model="dataForm.clientName" style="width: 100%"
                             :fetch-suggestions="querySearchClient" placeholder="请输入客户名称"
                             popper-class="select-option"
                             @select="handleClientSelect"></el-autocomplete>
          </el-form-item>
          <el-form-item label="职员" prop="staffName">
            <!--              <el-input v-model="dataForm.staffId" placeholder="职员"></el-input>-->
            <el-autocomplete v-model="dataForm.staffName" style="width: 100%"
                             :fetch-suggestions="querySearchStaff" placeholder="请输入职员名称"
                             popper-class="select-option"
                             @select="handleStaffSelect"></el-autocomplete>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="销售日期" prop="saleDate">
            <el-date-picker type="date" v-model="dataForm.saleDate" @on-change="_saleDateChange"
                            placeholder="销售日期" :editable="false" style="width: 100%"></el-date-picker>
          </el-form-item>
          <el-form-item label="交货日期" prop="deliveryDate">
            <el-date-picker type="date" v-model="dataForm.deliveryDate" @on-change="_deliverDateChange"
                            placeholder="交货日期" :editable="false" style="width: 100%"></el-date-picker>
          </el-form-item>
          <el-form-item label="安装地址" prop="productAddress">
            <el-autocomplete v-model="dataForm.productAddress" style="width: 100%"
                             :fetch-suggestions="querySearchProductAddress" placeholder="请输入安装地址"
                             popper-class="select-option"
            ></el-autocomplete>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="优惠率(%)" prop="discountRate">
            <el-input-number v-model="dataForm.discountRate" controls-position="right" style="width: 100%"
                             @input="calDiscount" @change="calDiscount"
                             :precision="2" :step="0.1" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="优惠金额(元)" prop="discountAmount">
            <el-input-number v-model="dataForm.discountAmount" controls-position="right" style="width: 100%"
                             :precision="2" :step="0.1" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="优惠后金额(元)" prop="totalAmount">
            <el-input-number v-model="dataForm.totalAmount" controls-position="right" style="width: 100%"
                             :precision="2" :step="0.1" :min="0"></el-input-number>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="定金(元)" prop="deposit">
            <el-input-number v-model="dataForm.deposit" controls-position="right" style="width: 100%"
                             :precision="2" :step="0.1" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="状态" size="mini" prop="status">
            <el-radio-group v-model="dataForm.status">
              <el-radio :label="0">新增</el-radio>
              <el-radio :label="1">缓冲</el-radio>
              <el-radio :label="2">待结算</el-radio>
              <el-radio :label="4">生产中</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="单据状态" size="mini" prop="warning">
            <el-radio-group v-model="dataForm.warning">
              <el-radio :label="0">正常</el-radio>
              <el-radio :label="1">异常</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <!--          </el-collapse-item>-->
          <!--          <el-collapse-item title="商品信息" name="2">-->
          <!--            <OrderDetails ref="orderDetailsData"></OrderDetails>-->
          <el-form-item>
            <!--        <el-button @click="getDataListByHeadId(this.dataForm.headerId)">查询</el-button>-->
            <el-button v-if="isAuth('sales:orderdetail:save')" type="primary" @click="addRow">添加</el-button>
            <el-button v-if="isAuth('sales:orderdetail:delete')" type="danger" @click="deleteHandle()"
                       :disabled="dataListSelections.length <= 0">批量删除
            </el-button>
          </el-form-item>
        </el-row>
        <el-form>
          <el-table
            :data="dataList"
            border
            :summary-method="getSummaries"
            show-summary
            v-loading="dataListLoading"
            @keyup.enter.native="addNewRow(dataList)"
            @selection-change="selectionChangeHandle"
            style="width: 100%; margin-top: 20px">
            <el-table-column
              type="selection"
              header-align="center"
              align="center"
              width="50">
            </el-table-column>
            <el-table-column
              prop="commodityName"
              header-align="center"
              align="center"
              width="250px"
              label="商品名称">
              <template slot-scope="scope">
                <el-autocomplete v-if="scope.row.status" v-model="scope.row.commodityName"
                                 :fetch-suggestions="querySearchAsync" placeholder="请输入内容"
                                 @select="handleNameSelect($event, scope.row)"
                                 popper-class="select-option"
                ></el-autocomplete>
                <span v-else>{{scope.row.commodityName}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="height"
              header-align="center"
              align="center"
              label="高">
              <template slot-scope="scope">
                <el-input v-if="scope.row.status" v-model="scope.row.height"
                          @keyup.native="scope.row.height = oninput(scope.row.height)"
                          @input="calSquares(scope.row)"></el-input>
                <span v-else>{{scope.row.height}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="width"
              header-align="center"
              align="center"
              label="宽">
              <template slot-scope="scope">
                <el-input v-if="scope.row.status" v-model="scope.row.width"
                          @keyup.native="scope.row.width = oninput(scope.row.width)"
                          @input="calSquares(scope.row)"></el-input>
                <span v-else>{{scope.row.width}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="count"
              header-align="center"
              align="center"
              label="数量">
              <template slot-scope="scope">
                <el-input v-if="scope.row.status" v-model="scope.row.count"
                          @keyup.native="scope.row.count = oninput(scope.row.count)"
                          @input="calSquares(scope.row),checkByDirectionNum(scope.row)"
                ></el-input>
                <span v-else>{{scope.row.count}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="direction"
              header-align="center"
              align="center"
              width="150px"
              label="方向">
              <template slot-scope="scope">
                <el-autocomplete v-if="scope.row.status" v-model="scope.row.direction"
                                 :fetch-suggestions="querySearchDirection" placeholder="请输入内容"
                                 @select="handleDirectionSelect($event, scope.row)"
                                 popper-class="select-option"></el-autocomplete>
                <span v-else>{{scope.row.direction}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="squares"
              header-align="center"
              align="center"
              label="面积">
              <template slot-scope="scope">
                <!--          <el-input v-if="scope.row.status" v-model="scope.row.squares"-->
                <!--                    @keyup.native="scope.row.squares = oninput(scope.row.squares)"></el-input>-->
                <!--          <span v-else>{{scope.row.squares}}</span>-->
                <!--          不可编辑-->
                <el-input v-if="0" v-model="scope.row.squares"
                          @keyup.native="scope.row.squares = oninput(scope.row.squares)"></el-input>
                <span v-else>{{scope.row.squares}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="materialName"
              header-align="center"
              align="center"
              width="150px"
              label="板材">
              <template slot-scope="scope">
                <el-autocomplete v-if="scope.row.status" v-model="scope.row.materialName"
                                 :fetch-suggestions="querySearchMaterial" placeholder="请输入内容"
                                 @select="handleMaterialSelect($event, scope.row)"
                                 popper-class="select-option"
                ></el-autocomplete>
                <span v-else>{{scope.row.materialName}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="colorName"
              header-align="center"
              align="center"
              width="150px"
              label="颜色">
              <template slot-scope="scope">
                <el-autocomplete v-if="scope.row.status" v-model="scope.row.colorName"
                                 :fetch-suggestions="querySearchColor" placeholder="请输入内容"
                                 @select="handleColorSelect($event, scope.row)"
                                 popper-class="select-option"
                ></el-autocomplete>
                <span v-else>{{scope.row.colorName}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="crafts"
              header-align="center"
              align="center"
              width="150px"
              label="特殊工艺名称">
              <template slot-scope="scope">
                <span>{{scope.row.crafts}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="craftsPrice"
              header-align="center"
              align="center"
              width="150px"
              label="特殊工艺单价(元)">
              <template slot-scope="scope">
                <span>{{scope.row.craftsPrice}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="salesAmount"
              header-align="center"
              align="center"
              label="销售金额(元)">
              <template slot-scope="scope">
                <!--          <el-input v-if="scope.row.status" v-model="scope.row.salesAmount"-->
                <!--                    ></el-input>-->
                <!--          不可编辑-->
                <el-input v-if="0" v-model="scope.row.salesAmount"
                          @keyup.native="scope.row.salesAmount = oninput(scope.row.salesAmount)"></el-input>
                <span v-else>{{scope.row.salesAmount}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="remark"
              header-align="center"
              align="center"
              width="150px"
              label="备注">
              <template slot-scope="scope">
                <el-input v-if="scope.row.status" v-model="scope.row.remark"></el-input>
                <span v-else>{{scope.row.remark}}</span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              header-align="center"
              align="center"
              width="120"
              label="操作">
              <template slot-scope="scope">
                <!--          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>-->
                <!--          <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>-->
                <el-button class="el-icon-edit" type="primary" :disabled="scope.row.status==1"
                           size="small" circle @click.native.prevent="editRow(scope.row)"></el-button>
                <el-button class="el-icon-delete" type="danger"
                           size="small" circle @click.native.prevent="deleteRow(scope.$index, dataList)"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
        </el-form>
        <!--          </el-collapse-item>-->
        <!--        </el-collapse>-->
      </div>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  // import OrderDetails from './orderdetail'
  // import Utils from '../../../utils/event.js'

  export default {
    // components: {
    //   OrderDetails
    // },
    data () {
      return {
        visible: false,
        infoVal: ['1', '2'], // 默认展开第一个
        dataForm: {
          headerId: 0,
          id: 0,
          name: '',
          code: '',
          clientId: '',
          clientName: '',
          staffId: '',
          staffName: '',
          saleDate: '',
          deliveryDate: '',
          storehouseId: 0,
          productAddress: '',
          remark: '',
          discountRate: 0,
          discountAmount: '',
          status: 0,
          warning: 0,
          totalAmount: '',
          deposit: ''
        },
        formDto: {
          orderDetailList: [],
          deleteOrderDetailList: []
        },
        clients: [],
        staffs: [],
        headSalesAmount: 0,
        names: [],
        directions: [],
        materials: [],
        colors: [],
        dataList: [],
        delList: [],
        salesAmount: 0,
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        dataRule: {
          name: [
            {required: true, message: '销售订单名不能为空', trigger: 'blur'}
          ],
          saleDate: [
            {required: true, message: '销售日期不能为空', trigger: 'blur'}
          ],
          deliveryDate: [
            {required: true, message: '交货日期不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    // // 钩子函数
    // mounted () {
    //   let that = this
    //
    //   Utils.$on('demo', function (msg) {
    //     console.log(msg)
    //     that.calDiscount()
    //   })
    // },
    activated () {
      this.getDataListByHeadId(this.dataForm.headerId)
    },
    methods: {

      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sales/orderheader/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.name = data.orderHeader.name
                this.dataForm.code = data.orderHeader.name
                this.dataForm.clientId = data.orderHeader.clientId
                this.dataForm.clientName = data.orderHeader.clientName
                this.dataForm.staffId = data.orderHeader.staffId
                this.dataForm.staffName = data.orderHeader.staffName
                this.dataForm.saleDate = data.orderHeader.saleDate
                this.dataForm.deliveryDate = data.orderHeader.deliveryDate
                // todo
                // this.dataForm.storehouseId = data.orderHeader.storehouseId
                this.dataForm.storehouseId = 0
                this.dataForm.productAddress = data.orderHeader.productAddress
                this.dataForm.remark = data.orderHeader.remark
                this.dataForm.discountRate = data.orderHeader.discountRate
                this.dataForm.discountAmount = data.orderHeader.discountAmount
                this.dataForm.totalAmount = data.orderHeader.totalAmount
                this.dataForm.deposit = data.orderHeader.deposit
                this.dataForm.status = data.orderHeader.status
                this.dataForm.warning = data.orderHeader.warning

                this.getDataListByHeadId(this.dataForm.id)
              }
            })
          } else {
            // this.dataForm.saleDate = data.orderHeader.saleDate
            // this.dataForm.deliveryDate = data.orderHeader.deliveryDate

            this.getDateTime()

            this.getDataListByHeadId(0)
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.calDiscount()

        if (this.dataForm.totalAmount < this.dataForm.deposit) {
          this.$message({
            message: '优惠后金额不得小于定金',
            type: 'warning'
          })
          return
        }

        // 订单明细
        this.formDto.orderDetailList = this.dataList
        this.formDto.deleteOrderDetailList = this.delList

        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/sales/orderheader/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'code': this.dataForm.name,
                'clientId': this.dataForm.clientId,
                'clientName': this.dataForm.clientName,
                'staffId': this.dataForm.staffId,
                'staffName': this.dataForm.staffName,
                'saleDate': this.dataForm.saleDate,
                'deliveryDate': this.dataForm.deliveryDate,
                // todo
                // 'storehouseId': this.dataForm.storehouseId,
                'storehouseId': 0,
                'productAddress': this.dataForm.productAddress,
                'remark': this.dataForm.remark,
                'discountRate': this.dataForm.discountRate,
                'discountAmount': this.dataForm.discountAmount,
                'totalAmount': this.dataForm.totalAmount,
                'deposit': this.dataForm.deposit,
                'status': this.dataForm.status,
                'warning': this.dataForm.warning,
                'salesOrderDetailList': this.formDto.orderDetailList,
                'deleteOrderDetailList': this.formDto.deleteOrderDetailList
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },

      _saleDateChange (data) {
        this.dataForm.saleDate = new Date(data)
      },
      _deliverDateChange (data) {
        this.dataForm.deliveryDate = new Date(data)
      },
      getDateTime () {
        // 销售日期，默认显示今天
        this.dataForm.saleDate = new Date()
        // 交货日期，默认显示今天+5天
        const end = new Date()
        end.setTime(end.getTime() + 3600 * 1000 * 24 * 5)
        this.dataForm.deliveryDate = this.formatDate(end)
      },
      /**
       * 格式化时间
       */
      formatDate (date) {
        let myyear = date.getFullYear()
        let mymonth = date.getMonth() + 1
        let myweekday = date.getDate()

        if (mymonth < 10) {
          mymonth = '0' + mymonth
        }
        if (myweekday < 10) {
          myweekday = '0' + myweekday
        }
        return myyear + '-' + mymonth + '-' + myweekday
      },

      // 获取最新的销售编号
      getLastSaleOrder (dataForm) {
        this.$http({
          url: this.$http.adornUrl(`/sales/orderheader/getLastSaleOrder`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            dataForm.name = data.lastOrderCode
          } else {
            dataForm.name = ''
          }
        })
      },

      // 客户 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchClient (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/client/listClients/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.clients = data.clientsMap.clientNameDtoList
          } else {
            this.clients = []
            this.$message.error(data.msg)
          }
        })
        // callback(this.clients)
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.clients)
        }, 500)
      },
      // 职员 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchProductAddress (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sales/orderheader/listProductAddress/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.staffs = data.productAddressMap.productAddressDtoList
          } else {
            this.staffs = []
            this.$message.error(data.msg)
          }
        })
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.staffs)
        }, 500)
        // callback(this.staffs)
      },
      // 安装地址 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchStaff (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/staff/listStaffs/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.staffs = data.staffsMap.staffNameDtoList
          } else {
            this.staffs = []
            this.$message.error(data.msg)
          }
        })
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.staffs)
        }, 500)
        // callback(this.staffs)
      },
      handleClientSelect (item) {
        console.log(item)
        // do something
        this.dataForm.clientId = item.clientId
        this.dataForm.clientName = item.value
      },
      handleStaffSelect (item) {
        console.log(item)
        // do something
        this.dataForm.staffId = item.staffId
        this.dataForm.staffName = item.value
      },
      calDiscount () {
        console.log('开始计算优惠金额:' + this.salesAmount)
        this.headSalesAmount = this.salesAmount

        if (!isNaN(this.headSalesAmount)) {
          this.dataForm.discountAmount = parseFloat(this.headSalesAmount * this.dataForm.discountRate / 100).toFixed(2)

          this.dataForm.totalAmount = parseFloat(this.headSalesAmount - this.dataForm.discountAmount).toFixed(2)
        }

        console.log('结束计算优惠金额：' + this.dataForm.totalAmount)
      },
      oninput (num) {
        let str = num
        let len1 = str.substr(0, 1)
        let len2 = str.substr(1, 1)
        // 如果第一位是0，第二位不是点，就用数字把点替换掉
        if (str.length > 1 && len1 === 0 && len2 !== '.') {
          str = str.substr(1, 1)
        }
        // 第一位不能是.
        if (len1 === '.') {
          str = ''
        }
        // 限制只能输入一个小数点
        if (str.indexOf('.') !== -1) {
          let str_ = str.substr(str.indexOf('.') + 1)
          if (str_.indexOf('.') !== -1) {
            str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
          }
        }
        // 正则替换
        str = str.replace(/[^\d.]/g, '') // 保留数字和小数点
        // str = str.replace(/\.\d\d\d$/, '') // 小数点后只能输两位
        return str
      },

      // 获取数据列表
      getDataListByHeadId (id) {
        this.dataForm.headerId = id || 0
        this.dataListLoading = true
        this.delList = []
        this.$http({
          url: this.$http.adornUrl(`/sales/orderdetail/listAllByHeadId`),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'headId': id
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
            this.$message.error(data.msg)
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataListByHeadId(this.dataForm.headerId)
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataListByHeadId(this.dataForm.headerId)
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.init(id)
        })
      },
      addNewRow (dataList) {
        if (dataList.length === 0) {

        } else {
          var n = dataList.length
          var data = dataList[n - 1]

          this.dataList.push({
            commodityId: data.commodityId,
            commodityName: data.commodityName,
            status: 1,
            warning: 0,
            // 商品单价
            commodityPrice: data.commodityPrice,
            // 商品数量
            // count: data.count,
            materialId: data.materialId,
            materialCode: data.materialCode,
            materialName: data.materialName,
            materialPrice: data.materialPrice,
            measurementId: data.measurementId,
            minSquares: data.minSquares,
            colorId: data.colorId,
            colorCode: data.colorCode,
            colorName: data.colorName,
            colorPrice: data.colorPrice,
            crafts: data.crafts,
            craftsPrice: data.craftsPrice,
            totalCraftsPrice: data.totalCraftsPrice
          })
        }
      },

      // 新增一行
      addRow () {
        this.dataList.push({
          salesAmount: 0,
          status: 1,
          warning: 0,
          // 商品单价
          commodityPrice: 0,
          // 商品数量
          count: '',
          // 板材单价
          materialPrice: 0,
          // 颜色单价
          colorPrice: 0,
          // 工艺单价
          craftsPrice: 0
        })
      },
      // 删除该行
      deleteRow (index, rows) {
        this.delList.push(rows[index].id)
        rows.splice(index, 1)
      },
      // 根据开启方向的数量检查合法性
      checkByDirectionNum (row) {
        if (!isNaN(row.directionNum) && !isNaN(row.count)) {
          let x = row.count % row.directionNum
          if (x === 0) {
            // 整除
          } else {
            row.direction = ''
            row.directionNum = 1
            row.count = 0

            this.calSquares(row)

            // 不能整除
            this.$message({
              message: '数量与开启方向不匹配',
              type: 'warning'
            })
          }
        }
      },
      // 计算面积
      calSquares (row) {
        // 计量单位ID，1为米，2为平方
        if (row.measurementId === 2) {
          if (!isNaN(row.height) && !isNaN(row.width) && !isNaN(row.count)) {
            const square = row.height * row.width / 1000000

            if (row.minSquares > square) {
              row.squares = row.minSquares * row.count
            } else {
              row.squares = parseFloat(square * row.count).toFixed(2)
            }
          } else {
            row.squares = 0
          }
        } else {
          row.squares = 0
        }

        this.calSalesAmount(row)
      },
      // 计算销售金额
      calSalesAmount (row) {
        console.log('开始计算销售金额')

        if (row.count === '') {
          row.count = 0
        }

        if (row.craftsPrice === '') {
          row.craftsPrice = '0'
        }

        row.totalCraftsPrice = row.craftsPrice * row.count

        // 计量单位ID，1为米，2为平方
        if (row.measurementId === 2) {
          // 按平方算
          // 销售金额 =  面积 *（商品单价 + 板材价格 + 颜色价格） + 工艺总价格
          row.salesAmount = parseFloat(row.squares * (row.commodityPrice + row.materialPrice + row.colorPrice) + row.totalCraftsPrice).toFixed(2)
        } else {
          // 按米算
          // 销售金额 =  高 * 商品数量 *（商品单价 + 板材价格 + 颜色价格） + 工艺总价格
          row.salesAmount = parseFloat(row.height / 1000 * row.count * (row.commodityPrice + row.materialPrice + row.colorPrice) + row.totalCraftsPrice).toFixed(2)
        }
        console.log('结束计算销售金额')
      },
      editRow (row) {
        row.status = 1
      },
      // 批量删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/sales/orderdetail/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataListByHeadId(this.dataForm.headerId)
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      // 合计
      getSummaries (param) {
        const {columns, data} = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          // 销售金额(元)
          if (column.property === 'salesAmount') {
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] += ''
            } else {
              sums[index] = ''
            }

            sums[index] = parseFloat(sums[index]).toFixed(2)

            this.salesAmount = sums[index]
          }
          // 数量
          if (column.property === 'count') {
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] += ''
            } else {
              sums[index] = ''
            }
          }
        })
        return sums
      },
      // 商品名称 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchAsync (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/commodity/listCommoditys/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.names = data.commoditysMap.commodityNameDtoList
          } else {
            this.names = []
            this.$message.error(data.msg)
          }
        })
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.names)
        }, 1000)
        // callback(this.names)
      },
      // 开启方向 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchDirection (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/direction/listDirections/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.directions = data.directionsMap.directionDtoList
          } else {
            this.directions = []
            this.$message.error(data.msg)
          }
        })
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.directions)
        }, 1000)
        // callback(this.directions)
      },
      // 板材 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchMaterial (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/material/listMaterials/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.materials = data.materialsMap.materialDtoList
          } else {
            this.materials = []
            this.$message.error(data.msg)
          }
        })
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.materials)
        }, 500)
        // callback(this.materials)
      },
      // 颜色 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchColor (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/color/listColors/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.colors = data.colorsMap.colorDtoList
          } else {
            this.colors = []
            this.$message.error(data.msg)
          }
        })
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.colors)
        }, 500)
        // callback(this.colors)
      },
      handleSelect (item) {
        console.log(item)
        // do something
      },
      handleNameSelect (item, row) {
        console.log(item)
        row.commodityName = item.commodityName
        row.commodityId = item.commodityId
        row.commodityPrice = item.commodityPrice
        row.crafts = item.craftName
        row.craftsPrice = item.craftPrice
        row.totalCraftsPrice = item.craftPrice * row.count
        row.measurementId = item.measurementId
        row.minSquares = item.minSquares
        this.calSquares(row)
      },

      handleMaterialSelect (item, row) {
        console.log(item)
        row.materialPrice = item.materialPrice
        row.materialCode = item.materialCode
        row.materialId = item.materialId
        this.calSquares(row)
      },
      handleDirectionSelect (item, row) {
        console.log(item)
        row.directionNum = item.directionNum
        this.checkByDirectionNum(row)
      },
      handleColorSelect (item, row) {
        console.log(item)
        row.colorPrice = item.colorPrice
        row.colorId = item.colorId
        this.calSquares(row)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .select-option {
    width: 600px;
  }
</style>
